###############################################################################
# MoveTopic.pl                                                                #
###############################################################################
# YaBB: Yet another Bulletin Board                                            #
# Open-Source Community Software for Webmasters                               #
# Version:        YaBB 2.2                                                    #
# Packaged:       November 8, 2007                                            #
# Distributed by: http://www.yabbforum.com                                    #
# =========================================================================== #
# Copyright (c) 2000-2007 YaBB (www.yabbforum.com) - All Rights Reserved.     #
# Software by:  The YaBB Development Team                                     #
#               with assistance from the YaBB community.                      #
# Sponsored by: Xnull Internet Media, Inc. - http://www.ximinc.com            #
#               Your source for web hosting, web design, and domains.         #
###############################################################################

$movetopicplver = 'YaBB 2.2 $Revision: 1.17 $';
if ($action eq 'detailedversion') { return 1; }

## move a thread, post level
sub MoveThread {
	$boardlist = "";
	my $boardId;
	my $threadToMove = $INFO{'thread'} || $FORM{'thread'};
	## to pull the current board out of the list, read the ctb file and match to the board name
	if(-e "$datadir/$threadToMove.ctb")	{
		&MessageTotals("load",$threadToMove);
		$boardId = ${$threadToMove}{'board'};
	}
	$currentboard = $boardId;
	&moveto;
	$yymain .= qq~
<table border="0" width="60%" cellspacing="1" class="bordercolor" cellpadding="4" align="center">
  <tr>
    <td class="titlebg"><b>$maintxt{'132'}</b></td>
  </tr><tr>
    <td class="windowbg" align="center">
    <script language="JavaScript1.2" src="$ubbcjspath" type="text/javascript"></script>
    <form action="$scripturl?action=movethread2;board=$INFO{'board'};thread=$INFO{'thread'}" method="post" name="move" onSubmit="return submitproc()"><br />
    <b>$maintxt{'133'}:</b> <select name="toboard">$boardlist</select>
	<input type="hidden" name="fromboard" value="$currentboard" />
    <input type="submit" value="$maintxt{'132'}" class="button" />
    </form>
    </td>
  </tr>
</table>
~;
	$yytitle = "$maintxt{'132'}";
	&template;
	exit;
}

sub MoveThread2 {
	# Admin / Mod Checks are lower down, so users deleting their own threads get moved to the binboard
	if ($iamguest) { &fatal_error("move_not_allowed"); }
	my ($thread, @messages, $newthreadid, $fromboard, $toboard, $recycle, $a, $inserted, @buffer, $OrigThreadLine, @origlinedatas, @toboardlinedatas);

	$thread = $FORM{'thread'} || $INFO{'thread'};
	if ($thread =~ /\D/) { &fatal_error("only_numbers_allowed"); }

	$fromboard = $FORM{'board'} || $INFO{'board'};
	if ($fromboard =~ m~/~)  { &fatal_error("no_board_slash"); }
	if ($fromboard =~ m~\\~) { &fatal_error("no_board_backslash"); }
	if (!$fromboard) {
		&MessageTotals("load", $thread);
		$fromboard = ${$thread}{'board'};
	}

	$toboard = $deleteboard || $FORM{'toboard'};
	if ($toboard =~ m~/~)  { &fatal_error("no_board_slash"); }
	if ($toboard =~ m~\\~) { &fatal_error("no_board_backslash"); }

	$recycle = $toboard eq $binboard ? 1 : 0;

	# thread check
	fopen(THREAD, "$datadir/$thread.txt") || &fatal_error("cannot_open","$datadir/$thread.txt", 1);
	@messages = <THREAD>;
	fclose(THREAD);
	chomp @messages;
	(undef, undef, undef, undef, $postername, undef) = split(/\|/, $messages[0]); # Get username of thread starter

	# Admin checks here, after we discover topic starters username
	unless ($iammod || $iamadmin || $iamgmod || ($username eq $postername && !$iamguest && !$exmem && $nodelallowed == 0) && $sessionvalid == 1) {
		&fatal_error("move_not_allowed");
	}

	# open fromboard, seek thread, if found then write a new thread
	$orgstate       = "";
	$OrigThreadLine = '';
	fopen(FROMBOARD, "+<$boardsdir/$fromboard.txt", 1) || &fatal_error("cannot_open","$boardsdir/$fromboard.txt", 1);
	seek FROMBOARD, 0, 0;
	@buffer = <FROMBOARD>;
	for ($a = 0; $a < @buffer; $a++) {
		if ($buffer[$a] =~ m~\A$thread\|~) {
			$OrigThreadLine = $buffer[$a];
			chomp $OrigThreadLine;

			if (!$recycle) {
				($mnum, $msub, $mname, $memail, $mdate, $mreplies, $musername, $micon, $mstate) = split(/\|/, $OrigThreadLine);

				if ($mstate !~ /0/) {
					$mstate .= "0";
					$OrigThreadLine = qq~$mnum|$msub|$mname|$memail|$mdate|$mreplies|$musername|$micon|$mstate~;
				}

				# Find a valid ID for new thread. New threadid is nearest moved thread
				$newthreadid = $thread + 1;
				while (-e "$datadir/$newthreadid.txt") { $newthreadid++; }

				# changes subject in message index to "Moved: Subject"
				$msub = qq~[m by=$username destboard=$toboard dest=$thread]: $msub~;

				# thread status - add (l)ocked and (m)oved - remove (a)nnoumcement
				## alter message icon to 'exclamation' to match 'lm'
				$mstate =~ s/a//ig;
				$mstate .= "lm";
				$orgstate = $mstate;
				$buffer[$a] = qq~$newthreadid|$msub|$mname|$memail|$mdate|0|$musername|exclamation|$mstate\n~;
			} else {
				$buffer[$a] = "";
			}
			last;
		}
	}
	unless ($OrigThreadLine) {
		fclose(FROMBOARD);
		&fatal_error("no_board_topic","$thread.");
	}
	truncate FROMBOARD, 0;
	seek FROMBOARD, 0, 0;
	print FROMBOARD @buffer;
	fclose(FROMBOARD);

	&MessageTotals("load", $thread);
	@tmprepliers = @repliers;

	# write new thread ('Moved:'+orig thread sub)
	if (!$recycle) {
		($tmpsub, undef) = split(/\|/, $messages[0],2);
		$tmpsub = qq~[m]: $tmpsub~;

		(undef, undef, undef, $tmpdate, undef) = split(/\|/, $messages[$#messages],5);
		my ($boardtitle, undef) = split(/\|/, $board{$toboard},2);

		$tmpmessage = "[moved] [link=$scripturl?num=$thread/0]" . "$boardtitle" . "[/link] [move by] ${$uid.$username}{'realname'}.";
		&FromChars($tmpmessage);
		fopen(NEWTHREAD, ">$datadir/$newthreadid.txt") || &fatal_error("cannot_open","$datadir/$newthreadid.txt", 1);
		print NEWTHREAD qq~$tmpsub|||$tmpdate|$username|exclamation|0|$user_ip|$tmpmessage|0|$date|$username|\n~;
		fclose(NEWTHREAD);

		# save newthread.ctb
		%$newthreadid = %$thread;
		${$newthreadid}{'replies'}      = 0;
		${$newthreadid}{'views'}        = 0;
		${$newthreadid}{'lastposter'}   = $username;
		${$newthreadid}{'threadstatus'} = $orgstate;
		&MessageTotals("update", $newthreadid);

		&modlog($newthreadid);
	}

	&UserAccount($username, "update", "lastpost") unless $recycle;

	# recount and set lastpost info of fromboard
	&BoardTotals("load", $fromboard);
	${$uid.$fromboard}{'threadcount'} -= $recycle;
	${$uid.$fromboard}{'messagecount'} = ${$uid.$fromboard}{'messagecount'} - ${$thread}{'replies'} - $recycle;
	&BoardTotals("update", $fromboard);
	&BoardSetLastInfo($fromboard);

	# write original thread to toboard
	@origlinedatas = split(/\|/, $OrigThreadLine);

	# set announcement state
	if ($toboard eq $annboard && $origlinedatas[8] !~ /a/i) { $origlinedatas[8] .= "a"; }
	elsif ($fromboard eq $annboard) { $origlinedatas[8] =~ s/a//ig; }
	if    ($toboard   eq $annboard) { $origlinedatas[8] =~ s/l//ig; }
	if    ($toboard   eq $annboard) { $origlinedatas[8] =~ s/s//ig; }
	$newstatus = $origlinedatas[8];

	$OrigThreadLine = join("|", @origlinedatas) . "\n";

	fopen(TOBOARD, "+<$boardsdir/$toboard.txt", 1) || &fatal_error("cannot_open","$boardsdir/$toboard.txt", 1);
	seek TOBOARD, 0, 0;
	@buffer = <TOBOARD>;
	truncate TOBOARD, 0;
	seek TOBOARD, 0, 0;

	$inserted = 0;
	for ($a = 0; $a < @buffer; $a++) {
		@toboardlinedatas = split(/\|/, $buffer[$a]);
		if (!$inserted && $toboardlinedatas[4] < $origlinedatas[4]) {
			print TOBOARD $OrigThreadLine;
			$inserted = 1;
		}
		print TOBOARD $buffer[$a];
	}
	if (!$inserted) {
		print TOBOARD $OrigThreadLine;
	}
	fclose(TOBOARD);

	# save changed thread.ctb
	@repliers = @tmprepliers;
	${$thread}{'threadstatus'} = $newstatus;
	${$thread}{'board'}        = $toboard;
	&MessageTotals("update", $thread);

	# recount and set lastpost info of toboard
	&BoardTotals("load", $toboard);
	${$uid.$toboard}{'threadcount'}++;
	${$uid.$toboard}{'messagecount'} = ${$uid.$toboard}{'messagecount'} + ${$thread}{'replies'} + 1;
	&BoardTotals("update", $toboard);
	&BoardSetLastInfo($toboard);

	# now fix all attachment board info
	for ($a = 0; $a < @messages; $a++) {
		(undef, undef, undef, undef, undef, undef, undef, undef, undef, undef, undef, undef, $mfn) = split(/\|/, $messages[$a]);
		if ($mfn) { $last; }
	}
	undef @messages;

	if ($mfn) {

		# change attachments board on topics
		fopen(AMP, "+<$vardir/attachments.txt", 1) || &fatal_error("cannot_open","$vardir/attachments.txt", 1);
		seek AMP, 0, 0;
		@buffer = <AMP>;
		truncate AMP, 0;
		for ($a = 0; $a < @buffer; $a++) {
			if ($buffer[$a] =~ m~\A$thread\|~) {
				chomp $buffer[$a];
				@attachfile = split(/\|/, $buffer[$a]);
				$attachfile[4] = $toboard;
				$buffer[$a] = join("|", @attachfile) . "\n";
			}
		}
		seek AMP, 0, 0;
		print AMP @buffer;
		fclose(AMP);
	}

	if ($INFO{'moveit'} != 1) {
		$yySetLocation = qq~$scripturl?num=$thread/0~;
		&redirectexit;
	}
}

1;
